package cn.haoxsf.app.config.wechat.uuuu;

import cn.haoxsf.app.common.api.enums.SystemExceptionEnum;
import cn.haoxsf.app.common.exception.BaseException;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: rest
 * @description: 微信模板通知工具
 * @author: Ele qvbanfm@qq.com
 * @create: 2019-12-26 13:27
 **/
@Component
@Log4j2
//@DependsOn(value = "wxMpService")
public class WeChatTemplateMsgUtils {
    @Autowired
    private WxMpService wxMpService;

    public String sendMessageToWeChat(String templateId, String openId, List<WxMpTemplateData> listData) {
        //实例化模板对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId(templateId);
        //设置发送给哪个用户
        wxMpTemplateMessage.setToUser(openId);

        //接收发送模板消息结果,就是msgid，if(msgid! = null)即成功
        String wxTemplateResult = null;
        //放进模板对象。准备发送
        wxMpTemplateMessage.setData(listData);
        try {
            //发送模板

            wxTemplateResult = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
            log.error("发送模板消息异常：{}", e.getMessage());
            throw new BaseException(SystemExceptionEnum.SERVER_ERROR.getCode(),e.getMessage());
        }
        return wxTemplateResult;
    }
}
